package system.service;

import com.jfinal.aop.Before;
import com.jfinal.aop.Duang;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import core.exception.AccountingException;
import system.dao.VoucherDetailDao;
import system.dao.VoucherHeadDao;
import system.dao.AccountSubjectDao;

import java.util.*;


public class VoucherService {
    VoucherHeadDao voucherHeadDao = Duang.duang(VoucherHeadDao.class);
    VoucherDetailDao voucherDetailDao = Duang.duang(VoucherDetailDao.class);
    AccountSubjectDao accountSubjectDao = Duang.duang(AccountSubjectDao.class);


    /**
     * 插入一张记账凭证
     *
     * @param record
     */
    @Before(Tx.class)
    public void insertJzpz(int jzpzId, Record record) {
        //获取head的Record
        Record head = new Record();

        head.set("voucher_id", jzpzId).setColumns(record).remove("voucher_detail");
        voucherHeadDao.insert(head);
        //获取detail集合
        List<Record> voucher_detail = record.get("voucher_detail");
        //调用dao,插入操作
        for (Record detail : voucher_detail) {
            detail.set("subject_id", accountSubjectDao.getIdByName((String) detail.get("subject_name")));
            detail.remove("subject_name");
        }
        int insert = voucherDetailDao.insert(voucher_detail, jzpzId);
        if (insert != voucher_detail.size()) {
            throw new AccountingException("错误:jzpz_detail成功插入数" + insert + "/" + voucher_detail);
        }
    }

    /**
     * 根据会计期间,获取当前登录用户在此期里的所有记账凭证信息
     *
     * @param period
     * @return
     */
    public List<Record> getVoucherList(String period) {
        List ids = voucherHeadDao.getIdsByPeriod(period);
        //根据id循环获取每一张记账凭证的信息
        List<Record> voucherList = new LinkedList();
        for (Object id : ids)
            voucherList.add(getVoucherInfoById((Integer) id));

        return voucherList;
    }

    /**
     * 根据一个id获取一张记账凭证的信息
     *
     * @param id
     * @return
     */
    public Record getVoucherInfoById(int id) {
        //获取记账凭证头
        Record head = voucherHeadDao.getById(id);

        //获取记账凭证细节
        List<Record> detail = voucherDetailDao.getListById(id);

        return new Record().set("head", head).set("detail", detail);
    }

    /**
     * 根据凭证编号删除记账凭证
     * @param voucher_id
     * @return
     */
    @Before(Tx.class)
    public void deleteVoucherByVoucherId(int... voucher_id) {
        final Set<Integer> ids = new LinkedHashSet();
        for (int id : voucher_id)
            ids.add(id);
        for (int id : ids) {
            //删除记账凭证头
            boolean b1 = voucherHeadDao.deleteById(id);
            //删除记账凭证细节
            boolean b2 = voucherDetailDao.deleteById(id);
            if (!b1)
                throw new AccountingException("删除记账凭证失败");
        }
    }
}
